<?php

namespace App\Repositories;


use App\Models\Module;
use App\Models\Permission;
use App\Models\Role;
use App\Models\RolePermission;
use App\Utils\Auth;
use App\Utils\Output;
use App\Utils\Pager;
use App\Utils\TreeUtil;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;

/**
 * Class RoleRepository
 * @package App\Repositories
 */
class RoleRepository
{
    function adminPager($params)
    {
        extract($params);
        $query = Role::query();
        if (!empty($keyword)) {
            $query->where(function (Builder $q) use ($keyword) {
                $q->orWhere('name', 'like', "%$keyword%");
                $q->orWhere('tag', 'like', "%$keyword%");
            });
        }
        return $query->paginate();
    }

    function editInfo($id)
    {
        $entity = Role::find($id);
        if ($entity) {
            return Output::data($entity);
        }
        return Output::fail("数据不存在");
    }

    function save($data, $id)
    {
        return Role::store($data, $id);
    }

    /**
     * 删除
     * @param $id
     * @return Output|int
     * @throws \Exception
     */
    function destroy($id)
    {
        return Role::destroy($id);
    }

    function rolePermissionLis($role_tag)
    {
        $permissions = Permission::query()
            ->leftJoin('role_permissions', function (JoinClause $q) use ($role_tag) {
                $q->on('role_permissions.permission_id', '=', 'permissions.id');
                $q->where('role_permissions.role_tag', '=', $role_tag);
                $q->where('role_permissions.deleted_at', '=', 0);
            })->select(
                'permissions.id as permission_id',
                'permissions.name',
                'permissions.module_id as pid'
            )
            ->selectRaw('-1 as id')
            ->selectRaw('case when role_permissions.permission_id>0 then 1 else 0 end checked')
            ->get()->toArray();
        $modules = Module::query()->get()->toArray();
        $lis = array_merge($permissions, $modules);
        $lis = TreeUtil::toTree($lis);
        return Output::data($lis);
    }

    function permissions($tag)
    {
        $permissions = Permission::query()
            ->join('role_permissions', function (JoinClause $q) use ($tag) {
                $q->on('role_permissions.permission_id', '=', 'permissions.id');
                $q->where('role_permissions.role_tag', '=', $tag);
                $q->where('role_permissions.deleted_at', '=', 0);
            })->select(
                'permissions.controller',
                'permissions.action'
            )->get();
        $codes = [];
        foreach ($permissions as $permission) {
            $codes[$permission->controller . '@' . $permission->action] = 1;
        }
        return $codes;
    }

    function menus()
    {
        $lis = Module::query()
            ->select('id', 'pid', 'name as title', 'url as href', 'tag', 'tag as icon', 'hide')
            ->orderByDesc('sort')
            ->get();
        $menus = TreeUtil::toTree($lis->toArray(), 'id', 'pid', 'children');
        $map = [];
        foreach ($menus as $key => $top) {
            if (isset($top['children'])) {
                foreach ($top['children'] as $k => $c) {
                    $map[$c['tag']] = [$top, $c];
                    if (!Auth::canAuth('index', $c['tag']) || $c['hide']) {
                        unset($menus[$key]['children'][$k]);
                    }
                }
                if (count($menus[$key]['children']) && !$top['hide']) {
                    $menus[$key]['children'] = array_values($menus[$key]['children']);
                } else {
                    unset($menus[$key]);
                }
            } else {
                unset($menus[$key]);
            }
        }
        return [array_values($menus), $map];
    }

    public function savePermission($tag, $permissions)
    {
        RolePermission::query()
            ->where('role_tag', '=', $tag)
            ->delete();
        $data = [];
        $time = time();
        foreach ($permissions as $permission) {
            $data[] = [
                'permission_id' => $permission,
                'role_tag' => $tag,
                'created_at' => $time,
                'updated_at' => $time
            ];
        }
        RolePermission::query()->insert($data);
        return Output::success('操作成功');
    }
}

